<template>
  <div>
    <div class="wallet-banner linear-bg-blue">
      <h1 class="big-amount" v-if="isAppreciation">{{balance}}</h1>
      <!-- 贝币 -->
      <h1 class="big-amount" v-if="!isAppreciation">{{paymentAssets}}</h1>
      <div class="smallBox">
        <h1 class="small-amount" v-if="isAppreciation">贝点：{{pointNum}}</h1>
        <h1 class="small-amount" v-if="!isAppreciation">增值贝点：{{paymentPoint}}</h1>
        <div class="tab" @click="tabClick">
          <img
            :src="isAppreciation ? 'https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/balanceTab2.png' : 'https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/balanceTab1.png'"
            mode="scaleToFill"
          />
        </div>
      </div>
      <p class="action">
        <span>帐户余额</span>
        <span @click="handleCharge" v-if="isAppreciation">充值</span>
        <span @click="handleTransfer">转账至云帐户</span>
      </p>
    </div>
    <div class="list">
      <i-tabs :current="activeType" color="#6692f7" @change="handleTabChange">
        <i-tab v-for="item in transType" :key="item.key" :title="item.name"></i-tab>
      </i-tabs>
      <!-- <div class="list-title" style="height:35px">
        <span class="col">内容</span>
        <span class="col">金额</span>
        <span class="col">点数</span>
        <span class="col">时间</span>
      </div>-->
      <scroll-view
        class="scroll-wrap no-scroll-bar"
        style="height:calc(100% - 42px - 36px)"
        scroll-y
        @scrolltolower="handleLoadMore"
      >
        <!-- <div v-for="(item,idx) in list" :key="idx" class="info-block">
          <span class="col ellipsis-2">{{item.content}}</span>
          <span class="col ellipsis-2">{{item.amount}}</span>
          <span class="col ellipsis-2">{{item.point}}</span>
          <span class="col ellipsis-2">{{item.createDate}}</span>
        </div>-->
        <div v-for="(item,idx) in list" :key="idx" class="new-info-block">
          <div class="left">
            <p>{{item.content}}</p>
            <span>{{item.createDate}}</span>
          </div>
          <div class="right">
            <div class="top">
              <p>贝币：</p>
              <span
                :class="item.amount >= 0 ? 'green' : 'orange'"
              >{{item.amount}}</span>
            </div>
            <div class="buttom">
              <p>贝点：</p>
              <span
                :class="item.point >= 0 ? 'green' : 'orange'"
              >{{item.point ? item.point : 0}}</span>
            </div>
          </div>
        </div>
        <p v-if="alreadyLastPage" class="end-tip">没有更多了</p>
      </scroll-view>
    </div>

    <div class="popup-window" :class="{show:showPopup}">
      <span class="close-icon" @click="handleHide">&times;</span>
      <div v-if="!qrURL&&!isTransfer" key="1" class="popup-wrap">
        <input
          v-model="orderAmount"
          class="input-block"
          type="digit"
          placeholder="请输入充值金额"
          placeholder-class="placeholder-part"
          @change="orderAmountChange"
        />
        <div class="popup-btn-wrap">
          <span class="cancel-btn" @click="handleHide">取消</span>
          <span class="confirm-btn" @click="chargeAccount">确定</span>
        </div>
      </div>
      <div v-else-if="isTransfer" key="2" class="popup-wrap">
        <input
          v-model="orderAmount"
          class="input-block"
          type="digit"
          placeholder="请输入转账金额"
          placeholder-class="placeholder-part"
          @change="orderAmountChange"
        />
        <div class="popup-btn-wrap">
          <span class="cancel-btn" @click="handleHide">取消</span>
          <span class="confirm-btn" @click="transferToCloudAccount">确定</span>
        </div>
      </div>
      <div v-else key="3" class="qr-wrap">
        <img :src="qrURL" mode="aspectFit" class="qr-code" />
        <p class="tip">请识别二维码进行支付</p>
        <button class="btn-color-blue" @click="scanPayOrder">我已完成支付</button>
      </div>
    </div>
  </div>
</template>

<script>
import { getCurrentPageParams } from '@/utils'
import {
  FIND_SHOP_BASE_INFO,
  FIND_SHOP_BUSINESS_LOG_PAGE,
  CHARGE_ACCOUNT,
  FIND_CHARGE_ACCOUNT_ORDER,
  FIND_TRANSFER_TO_CLOUD_ACCOUNT_TAX,
  TRANSFER_TO_CLOUD_ACCOUNT,
  FIND_USER_OPEN_ID
} from '@/api'
import { Base64 } from 'js-base64'

export default {
  components: {},
  props: {},
  data () {
    return {
      freeAssets: '',
      pointNum: '',
      paymentPoint: '',
      paymentAssets: '',
      currentPage: 1,
      activeType: '0',
      transType: [
        { key: '0', name: '明细' },
        { key: '1', name: '返佣' }
        // { key: '2', name: '积分类型' }
      ],
      logList: [],
      alreadyLastPage: false,
      showPopup: false,
      orderAmount: '',
      orderNum: '',
      qrURL: '',
      isTransfer: false,
      transferSuccess: false,
      openId: '',
      isAppreciation: true
    }
  },
  computed: {
    account () {
      return this.$store.state.account
    },
    balance () {
      if (this.freeAssets || this.freeAssets === 0) {
        return '￥' + (this.freeAssets * 0.01).toFixed(2)
      } else {
        return ''
      }
    },
    list () {
      return this.logList.map(_ => ({
        amount: (_.amount * 0.01).toFixed(2),
        content: _.content,
        createDate: _.createDate,
        point: _.point || ''
      }))
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {
    this.getwxCode()
    this.getShopBaseInfo()
    this.getTransLog()
    this.isAppreciation = true
    if (getCurrentPageParams('isRebate') === '1') {
      this.activeType = '1'
    } else {
      this.activeType = '0'
    }
  },
  methods: {
    tabClick () {
      const vm = this
      vm.init()
      if (vm.isAppreciation) {
        vm.isAppreciation = false
        vm.getTransLog()
      } else {
        vm.isAppreciation = true
        vm.getTransLog()
      }
    },
    handleTabChange (e) {
      let key = e.target.key
      this.activeType = key

      this.currentPage = 1
      this.getTransLog()
    },
    handleCharge () {
      this.isTransfer = false
      this.showPopup = true
    },
    handleTransfer () {
      this.isTransfer = true
      this.showPopup = true
    },
    handleLoadMore () {
      if (!this.alreadyLastPage) {
        this.getTransLog()
      }
    },
    handleHide () {
      const vm = this
      vm.showPopup = false
      setTimeout(() => {
        if (vm.orderNum || vm.transferSuccess) {
          vm.getShopBaseInfo()
        }

        vm.orderAmount = ''
        vm.orderNum = ''
        vm.qrURL = ''
        vm.isTransfer = false
        vm.transferSuccess = false
      }, 300)
    },

    getShopBaseInfo () {
      const vm = this

      FIND_SHOP_BASE_INFO(vm.account.shopId)
        .then(r => {
          if (r.data.code === '0') {
            vm.freeAssets = r.data.data.assets // 余额
            vm.pointNum = r.data.data.point // 贝点
            vm.paymentAssets = `￥${(r.data.data.paymentAssets * 0.01).toFixed(
              2
            )}` // 贝币（增值余额）
            vm.paymentPoint = r.data.data.paymentPoint // 增值贝点
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    getTransLog () {
      const vm = this
      let params = {
        shopId: vm.account.shopId,
        transType: vm.activeType
      }
      if (vm.isAppreciation) {
        params.accountType = 'NORMAL'
      } else {
        params.accountType = 'PAYMENT'
      }

      FIND_SHOP_BUSINESS_LOG_PAGE(params, vm.currentPage, 10)
        .then(r => {
          if (r.data.code === '0') {
            let { list, isFirstPage, isLastPage } = r.data.data
            vm.printList(list, isFirstPage, isLastPage)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    printList (list, isFirst, isLast) {
      if (isFirst) {
        this.logList = list
        if (isLast || !list.length) {
          // only one page
          this.alreadyLastPage = true
        } else {
          // has next page
          this.alreadyLastPage = false
          this.currentPage += 1
        }
      } else if (isLast) {
        // more than one page and this is the last page
        this.logList.push(...list)
        this.alreadyLastPage = true
      } else {
        // middle page
        this.logList.push(...list)
        this.alreadyLastPage = false
        this.currentPage += 1
      }
    },
    orderAmountChange (e) {
      this.orderAmount = e.target.value
    },
    chargeAccount () {
      const vm = this

      if (!vm.orderAmount) {
        vm.$toast('请输入充值金额')
        return false
      }

      let params = {
        amount: vm.orderAmount * 1,
        // paySourceEnum: 'APP',
        providerId: vm.account.providerId,
        relateMan: vm.account.shopId,
        storeIdentityEnum: 'SHOP',
        openId: vm.openId,
        payMerId: vm.$store.state.payMerId,
        payMethodEnum: 'MINI', // 之前是改了的WECHAT
        paySourceEnum: 'H5' // 之前是改了的MINI
      }

      CHARGE_ACCOUNT(params)
        .then(r => {
          if (r.data.code === '0') {
            if (r.data.data && r.data.data.data) {
              let payInfo = Base64.decode(r.data.data.data)
              vm._callWechatPay(JSON.parse(payInfo))
              vm.handleHide()
            }
            // vm.qrURL = 'data:image/png;base64,' + r.data.data.data
            // vm.orderNum = r.data.data.orderNum
          } else if (r.data.message === '未找到云账户信息') {
            vm
              .$alert(
                '您暂未开通云账户，请到爱卡卡开店宝pc端管理系统登录开通。详情请咨询400-888-5115'
              )
              .then(r => {
                vm.$router.go(-1)
              })
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {})
    },
    getwxCode () {
      const vm = this
      wx.login({
        timeout: 6000,
        success: function (res) {
          vm._getWxCode(res.code)
        },
        fail: function (err) {
          console.error(err)
        }
      })
    },
    _getWxCode (code) {
      const vm = this
      let appId = vm.$store.state.appId
      let appSecret = Base64.decode(vm.$store.state.appSecret)
      FIND_USER_OPEN_ID(appId, appSecret, code)
        .then(r => {
          if (r.data.code === '0') {
            vm.openId = r.data.data
          } else {
            this.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    },
    // 2019/5/22 新加的
    _callWechatPay (payInfo) {
      const vm = this

      wx.requestPayment({
        ...payInfo,
        success: function (res) {
          vm.$alert('支付成功', '').then(() => {
            vm.$router.go(-1)
          })
        },
        fail: function (err) {
          if (err.errMsg === 'requestPayment:fail cancel') {
          } else {
            vm.$toast('支付失败')
          }
        }
      })
    },
    // 2019/5/22 新加的

    scanPayOrder () {
      const vm = this

      FIND_CHARGE_ACCOUNT_ORDER(vm.orderNum)
        .then(r => {
          if (r.data.code === '0') {
            if (r.data.data && r.data.data.state) {
              // charge success
            } else {
              vm.$toast('支付信息未找到，请稍后再试')
            }
            setTimeout(() => {
              vm.handleHide()
            }, 300)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    transferToCloudAccount () {
      const vm = this

      if (!vm.orderAmount) {
        vm.$toast('请输入转账金额')
        return false
      }

      let params = {
        identity: 'SHOP',
        orderAmount: vm.orderAmount * 100,
        relateMan: vm.account.shopId
      }
      if (!vm.isAppreciation) {
        params.transferType = 'PAYMENT'
      } else {
        delete params.transferType
      }

      FIND_TRANSFER_TO_CLOUD_ACCOUNT_TAX(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.confirmTransfer(r.data.data)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    confirmTransfer (obj) {
      const vm = this

      vm
        .$dialog(
          `实际到账${obj.amount * 0.01}元，税率${obj.withdrawTaxRatio *
            100}%，是否要转账？`
        )
        .then(r => {
          vm.startTransfer()
        })
        .catch(e => {
          // cancel
          // do nothing
        })
    },
    startTransfer () {
      const vm = this

      let params = {
        identity: 'SHOP',
        orderAmount: vm.orderAmount * 100,
        relateMan: vm.account.shopId
      }
      if (!vm.isAppreciation) {
        params.transferType = 'PAYMENT'
      } else {
        delete params.transferType
      }

      TRANSFER_TO_CLOUD_ACCOUNT(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.transferSuccess = true
            vm.$toast('操作成功')
            vm.handleHide()
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    init () {
      const vm = this
      vm.logList = []
      vm.currentPage = 1
      vm.alreadyLastPage = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';

.smallBox {
  display: flex;
  justify-content: space-between;
  > .tab {
    // margin-right: 20px;
    // background: #000;
    // opacity: 0.5;
    // padding: 3px 8px;
    // position: relative;
    img {
      width: 65px;
      height: 25px;
      // position: absolute;
      // top: 50%;
      // left: 50%;
      // transform: translate(-50%, -50%);
      // z-index: 2;
    }
  }
}
.action {
  padding: 0;
}
.list {
  height: calc(100% - 120px + 35px);
  // > .list-title {
  //   padding: 0 15px;
  //   font-size: 15px;
  //   display: flex;
  //   align-items: center;
  //   justify-content: space-between;
  //   border-bottom: 1px solid $light-gray;
  //   > .col {
  //     color: $gray;
  //     width: 25%;
  //     text-align: center;
  //   }
  // }
  > .scroll-wrap {
    box-sizing: border-box;
    padding: 0 15px;
    // .info-block {
    //   font-size: 14px;
    //   padding: 10px 0;
    //   border-bottom: 1px solid $light-gray;
    //   display: flex;
    //   justify-content: space-between;
    //   align-items: center;
    //   > .col {
    //     width: 25%;
    //     text-align: center;
    //   }
    // }
    .new-info-block {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 13px;
      padding: 10px 0;
      .left {
        p {
          color: #000;
        }
        span {
          color: $gray;
        }
      }
      .right {
        width: 40%;
        div {
          display: flex;
          justify-content: space-between;
          p {
            color: #000;
          }
          .green {
            color: green;
          }
          .orange {
            color: $orange;
          }
        }
      }
    }
    .end-tip {
      margin: 0;
      padding: 15px;
      text-align: center;
      color: $gray;
      font-size: 15px;
    }
  }
}
.popup-window {
  display: flex;
  justify-content: center;
  align-items: center;
  > .popup-wrap,
  > .qr-wrap {
    background-color: $white;
    width: 280px;
    border-radius: 8px;
    padding: 15px 15px 60px;
    position: relative;
    overflow: hidden;
    > .input-block {
      width: calc(100% - 20px);
      padding: 5px 10px;
      font-size: 15px;
      border: 1px solid $light-gray;
      border-radius: 4px;
    }
    > .popup-btn-wrap {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1px solid $light-gray;
      > .cancel-btn,
      > .confirm-btn {
        width: 50%;
        height: 40px;
        line-height: 40px;
        font-size: 15px;
        text-align: center;
        background-color: $white;
        &.confirm-btn {
          color: $blue;
          border-left: 1px solid $light-gray;
        }
      }
    }
  }
  > .qr-wrap {
    > .qr-code {
      width: 250px;
      height: 250px;
    }
    > .tip {
      font-size: 12px;
      color: $blue;
      text-align: center;
    }
    > .btn-color-blue {
      position: absolute;
      bottom: 20px;
      left: 15px;
      width: calc(100% - 30px);
    }
  }
}
</style>
